package com.g8.pethospitallearnbackend.service.impls;

import cn.hutool.core.lang.Dict;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import com.g8.pethospitallearnbackend.entity.*;
import com.g8.pethospitallearnbackend.exception.CustomException;
import com.g8.pethospitallearnbackend.mapper.*;
import com.g8.pethospitallearnbackend.service.EmailService;
import com.g8.pethospitallearnbackend.service.ExamService;
import com.g8.pethospitallearnbackend.service.PaperService;
import com.g8.pethospitallearnbackend.service.QuestionService;
import com.g8.pethospitallearnbackend.utils.NewIdGenerateUtil;
import com.g8.pethospitallearnbackend.utils.ValidateUtil;
import com.g8.pethospitallearnbackend.utils.responseUtil.ResponseStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class ExamServiceImpl implements ExamService {
    @Autowired
    ExamMapper examMapper;

    @Autowired
    ExamInternMapper examInternMapper;

    @Autowired
    PaperService paperService;

    @Autowired
    UserMapper userMapper;

//    @Autowired
//    QuestionMapper questionMapper;

    @Autowired
    QuestionService questionService;

    @Autowired
    ExamStuQuesMapper examStuQuesMapper;

    @Autowired
    EmailService emailService;


    @Override
    public List<Exam> getAllExam() {
        ExamExample example = new ExamExample();
        List<Exam> list = examMapper.selectByExample(example);
        if (list.isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "请求数据为空");
        }
        for(int i=0;i<list.size();i++){
            Exam exam = list.get(i);
            String examId = exam.getExamId();
            exam = getExamById(examId);
            list.get(i).setPaper(exam.getPaper());
            list.get(i).setExamStus(exam.getExamStus());
        }
        return list;
    }

    @Override
    public Exam getExamById(String examId) {
        //先根据examId找到这场考试
        Exam exam = examMapper.selectByPrimaryKey(examId);
        if (exam == null) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "请求考试未找到");
        }
        if (exam != null) {
            //根据试卷id找到该场考试的试卷
            Paper paper = paperService.getPaperById(exam.getPaperId());
            //把上面找到的试卷存入Exam类中
            exam.setPaper(paper);
            //把和考试相关的所有的学生的信息都找到，存入列表
            ExamInternExample example = new ExamInternExample();
            example.createCriteria().andExamIdEqualTo(examId);
            List<ExamIntern> list = examInternMapper.selectByExample(example);
            //处理列表，找到所有参加的学生，把学生和考试相关的信息都放在新增类ExamStu的List里
            List<Exam.ExamStu> examStus = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                //将List中每一条的id time grade提取出来放在新增类里
                String stuId = list.get(i).getUserId();
                LocalDateTime time = list.get(i).getEnterTime();
                Integer grade = list.get(i).getGrade();
                Exam.ExamStu examStu = new Exam.ExamStu(stuId, time, grade);
                //类放到列表里
                examStus.add(examStu);
            }
            exam.setExamStus(examStus);
        }

        return exam;
    }

    @Override
    public List<Exam> searchExam(String searchExam) {
        searchExam = "%" + searchExam + "%";
        ExamExample example = new ExamExample();
        example.createCriteria().andExamNameLike(searchExam);
        List<Exam> exams = examMapper.selectByExample(example);
        if (exams.isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "请求数据为空");
        }
        return exams;
    }

    @Override
    public Exam addExam(Exam exam) {
        //检查传入的信息是否为空
        if (exam.getExamName() == null || exam.getExamName().isEmpty()
                || exam.getExamDdl() == null || exam.getExamDdl().toString().isEmpty()
                || exam.getExamStus() == null || exam.getExamStus().isEmpty()
                || exam.getExamTime() == null || exam.getExamTime().toString().isEmpty()
                || exam.getPaperId() == null || exam.getPaperId().isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "上传数据不完整，请补充完整后添加");
        }

        //考试名称不能一样！
        ExamExample example11 = new ExamExample();
        example11.createCriteria().andExamNameEqualTo(exam.getExamName());
        List<Exam> exams11 = examMapper.selectByExample(example11);
        if(!exams11.isEmpty()){
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "试卷名称重复，请重新取名！");
        }

        //检查传入信息的合理性
        if (exam.getExamName().length() >= 30 || exam.getExamTime() <= 0) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "试卷名过长或考试时间不合理，请重新设置！");
        }

        //查看paper是否存在
        Paper paper1 = paperService.getPaperById(exam.getPaperId());
        if (paper1 == null) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您添加的试卷不存在，请重新添加");
        }
        //随机生成3位examId
        String id = NewIdGenerateUtil.getNumber(3);
        Exam repeat = examMapper.selectByPrimaryKey(id);
        while (repeat != null) {
            id = NewIdGenerateUtil.getNumber(3);
            repeat = examMapper.selectByPrimaryKey(id);
        }
        exam.setExamId(id);
        //补充完整exam中的Paper
        Paper paper = paperService.getPaperById(exam.getPaperId());
        exam.setPaper(paper);
        //补充完整exam中的examStus
        List<Exam.ExamStu> examStuList = exam.getExamStus();
        for (int i = 0; i < examStuList.size(); i++) {
            //遍历
            Exam.ExamStu examStu = examStuList.get(i);
            //查看添加的实习生是否存在
            String stuId = examStu.getStuId();
            UserExample userExample = new UserExample();
            userExample.createCriteria().andUserIdEqualTo(stuId).andUserRoleEqualTo((byte) 1);
            List<User> users = userMapper.selectByExample(userExample);
            if (users.isEmpty()) {
                throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您添加的应考实习生不存在，请重新添加");
            }
        }
        //发现可以不用补充完整，因为新建一个考试 那么关于学生的enterTime，grade就都是null
        //将exam插入到数据库
        examMapper.insert(exam);
        //然后补充完整数据库中exam_intern表
        for (int i = 0; i < examStuList.size(); i++) {
            //遍历
            Exam.ExamStu examStu = examStuList.get(i);
            ExamIntern examIntern = new ExamIntern();
            String stuId = examStu.getStuId();
            examIntern.setExamId(exam.getExamId());
            examIntern.setUserId(stuId);
            //插入
            examInternMapper.insert(examIntern);

            //发送考试通知邮件
            User user = userMapper.selectByPrimaryKey(stuId);
            String email = user.getUserEmail();
            String name = user.getUserName();
            sendEmail(email, exam.getExamName(), exam.getExamDdl(), name);
        }
        return exam;
    }

    @Override
    public String sendEmail(String email, String exam, LocalDateTime ddl, String name) {
        // 先校验一下邮箱格式
        if (!ValidateUtil.isEmail(email)) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "邮箱格式错误");
        }
        //修改时间格式
        String ddltime = ddl.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss"));
        // 获取发送邮箱验证码的HTML模板
        TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("templates", TemplateConfig.ResourceMode.CLASSPATH));
        Template template = engine.getTemplate("email-examNotice.ftl");

        // 发送邮件
        emailService.sendComplexEmail(new EmailSend(email,
                "虚拟宠物医院考试通知", template.render(Dict.create().set("name", name).set("exam",exam).set("ddl",ddltime))));

        return "发送邮件通知成功";

    }

    @Override
    public Exam changeExam(Exam exam) {
        //检查传入的信息是否为空
        if (exam.getExamName() == null || exam.getExamName().isEmpty()
                || exam.getExamDdl() == null || exam.getExamDdl().toString().isEmpty()
                || exam.getExamStus() == null || exam.getExamStus().isEmpty()
                || exam.getExamTime() == null || exam.getExamTime().toString().isEmpty()
                || exam.getPaperId() == null || exam.getPaperId().isEmpty()
                || exam.getExamId() == null || exam.getExamId().isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "上传数据不完整，请补充完整后添加");
        }

//        //检查考试是否有考生已经参加，如果已经有考生参加则不允许修改
//        String examId = exam.getExamId();
//        ExamInternExample exampletemp = new ExamInternExample();
//        exampletemp.createCriteria().andExamIdEqualTo(examId).andEnterTimeIsNotNull().andGradeIsNotNull();
//        List<ExamIntern> examInternstemp = examInternMapper.selectByExample(exampletemp);
//        if(!examInternstemp.isEmpty()){
//            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您所要修改的考试已经有实习生参加并生成记录，题目部分不允许修改！");
//        }

        //检查数据库中是否存在需要修改的考试
        Exam exam1 = examMapper.selectByPrimaryKey(exam.getExamId());
        if (exam1 == null) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您要修改的考试不存在，请重新选择");
        }

        //考试名称不能一样！
        ExamExample example11 = new ExamExample();
        example11.createCriteria().andExamNameEqualTo(exam.getExamName()).andExamIdNotEqualTo(exam.getExamId());
        List<Exam> exams11 = examMapper.selectByExample(example11);
        if(!exams11.isEmpty()){
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "试卷名称重复，请重新取名！");
        }

        //查看paper是否存在
        Paper paper1 = paperService.getPaperById(exam.getPaperId());
        if (paper1 == null) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您添加的试卷不存在，请重新添加");
        }

        //检查考试是否有考生已经参加，如果已经有考生参加则不允许修改考试的试卷
        String examId = exam.getExamId();
        String paperOrigId = examMapper.selectByPrimaryKey(examId).getPaperId();
        if (!paper1.getPaperId().equals(paperOrigId)) {
            ExamInternExample exampletemp = new ExamInternExample();
            exampletemp.createCriteria().andExamIdEqualTo(examId).andEnterTimeIsNotNull().andGradeIsNotNull();
            List<ExamIntern> examInternstemp = examInternMapper.selectByExample(exampletemp);
            if (!examInternstemp.isEmpty()) {
                throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您所要修改的考试已经有实习生参加并生成记录，考卷部分不允许修改！");
            }
        }

        //补充完整exam中的Paper
        Paper paper = paperService.getPaperById(exam.getPaperId());
        exam.setPaper(paper);

        //补充完整examStus
        List<Exam.ExamStu> examStuList = exam.getExamStus();
        for (int i = 0; i < examStuList.size(); i++) {
            Exam.ExamStu examStu = examStuList.get(i);
            //查看添加的实习生是否存在
            String stuId = examStu.getStuId();
            UserExample userExample = new UserExample();
            userExample.createCriteria().andUserIdEqualTo(stuId).andUserRoleEqualTo((byte) 1);
            List<User> users = userMapper.selectByExample(userExample);
            if (users.isEmpty()) {
                throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您添加的应考实习生不存在，请重新添加");
            }
        }

        //在数据库中修改
        examMapper.updateByPrimaryKey(exam);

        //更新数据库的exam_intern表
        //先删除和exam相关的所有
        ExamInternExample example = new ExamInternExample();
        example.createCriteria().andExamIdEqualTo(exam.getExamId());
        examInternMapper.deleteByExample(example);
        //然后将新的插入
        for (int i = 0; i < examStuList.size(); i++) {
            //遍历
            Exam.ExamStu examStu = examStuList.get(i);
            ExamIntern examIntern = new ExamIntern();
            String stuId = examStu.getStuId();
            examIntern.setExamId(exam.getExamId());
            examIntern.setUserId(stuId);
            //插入
            examInternMapper.insert(examIntern);

            //发送考试通知邮件
            User user = userMapper.selectByPrimaryKey(stuId);
            String email = user.getUserEmail();
            String name = user.getUserName();
            sendEmail(email, exam.getExamName(), exam.getExamDdl(), name);
        }

        return exam;
    }

    @Override
    public String deleteExam(String examId) {
        //检查传入的信息是否完整
        if (examId == null || examId.isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "传入的examId为空，请重新输入");
        }

        //检查要删除的考试是否存在
        Exam exam1 = examMapper.selectByPrimaryKey(examId);
        if (exam1 == null) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您要删除的考试不存在，请重新选择");
        }

//        //检查考试是否有考生已经参加，如果已经有考生参加则不允许删除
//        ExamInternExample examInternExample = new ExamInternExample();
//        examInternExample.createCriteria().andExamIdEqualTo(examId).andEnterTimeIsNotNull();
//        List<ExamIntern> examInternList = examInternMapper.selectByExample(examInternExample);
//        if(!examInternList.isEmpty()){
//            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "你要删除的考试已经有考生参加，不许删除");
//        }


        examMapper.deleteByPrimaryKey(examId);

        return "删除成功";
    }

    //返回实习生参加过的考试列表
    @Override
    public List<Exam> userExam1(String userId) {
        //先判断传入的用户id是否完整
        if (userId == null || userId.isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您传入的用户id不完整，请重新选择");
        }

        //判断数据库中是否有该用户
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您要查询的考生不存在，请重新选择");
        }

        //在exam_intern表中找到该考生成绩不为null的考试
        List<Exam> exams = new ArrayList<>();
        ExamInternExample example = new ExamInternExample();
        example.createCriteria().andUserIdEqualTo(userId).andGradeIsNotNull().andEnterTimeIsNotNull();
        List<ExamIntern> examInterns = examInternMapper.selectByExample(example);
        for (int i = 0; i < examInterns.size(); i++) {
            String examId = examInterns.get(i).getExamId();
            Exam exam = examMapper.selectByPrimaryKey(examId);
            exams.add(exam);
        }

        return exams;
    }

    //返回实习生没参加过的考试列表
    @Override
    public List<Exam> userExam0(String userId) {
        //先判断传入的用户id是否完整
        if (userId == null || userId.isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您传入的用户id不完整，请重新选择");
        }

        //判断数据库中是否有该用户
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您要查询的考生不存在，请重新选择");
        }

        //在exam_intern表中找到该考生成绩为null的考试
        List<Exam> exams = new ArrayList<>();
        ExamInternExample example = new ExamInternExample();
        example.createCriteria().andUserIdEqualTo(userId).andGradeIsNull().andEnterTimeIsNull();
        List<ExamIntern> examInterns = examInternMapper.selectByExample(example);
        for (int i = 0; i < examInterns.size(); i++) {
            String examId = examInterns.get(i).getExamId();
            Exam exam = examMapper.selectByPrimaryKey(examId);
            exams.add(exam);
        }

        return exams;
    }

    @Override
    public List<ExamStuQues> submitExam(ExamStuSubmit examStuSubmit) {
        //用于实习生此次考试成绩
        int grade = 0;
        List<ExamStuQues> examStuQuesList = new ArrayList<>();

        //检查传入的数据是否为空
        if (examStuSubmit == null || examStuSubmit.toString().isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您传入的信息为空，请重新提交");
        }

        //拆分传入的数据
        String stuId = examStuSubmit.getStuId();
        String examId = examStuSubmit.getExamId();
        LocalDateTime enterTime = examStuSubmit.getEnterTime();
        //submitquesattempt即quesId+attempt
        List<SubmitQuesAttempt> submitQuesAttemptList = examStuSubmit.getSubmitQuesAttemptList();
        if (submitQuesAttemptList.isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您传入的题目和答案列表为空，请重新提交");
        }

        //检查每一部分的是否完整
        if (stuId == null || stuId.isEmpty() || enterTime == null || enterTime.toString().isEmpty()
                || examId == null || examId.isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您传入的id或时间为空，请重新提交");
        }
        //拿到此次考试的所有信息
        Exam exam = getExamById(examId);
        Exam exam1 = examMapper.selectByPrimaryKey(examId);
        if (exam1 == null) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您要提交的考试不存在，请重试");
        }
        Paper paper = exam.getPaper();
        //拿到paperQues 即Question+Score
        List<Paper.PaperQues> paperQuesList = paper.getPaperQuesList();
        //题目是否都有答案不再做判断，答案为空的题目直接按0分处理~

        //检查提交的题目数量和试卷的题目数量是否一致
        if (submitQuesAttemptList.size() != paperQuesList.size()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您要提交的题目数量与试卷题目总数不一致，请重新提交");
        }

        //检查exam_intern表数据
        ExamInternExample examInternExample = new ExamInternExample();
        examInternExample.createCriteria().andExamIdEqualTo(examId).andUserIdEqualTo(stuId)
                .andEnterTimeIsNull().andGradeIsNull();
        List<ExamIntern> examInterns = examInternMapper.selectByExample(examInternExample);
        //检查数据库中存储的exam_intern数据是否正常
        if (examInterns.size() != 1) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "数据库中存储的该场考试与考生的数据异常，请重试");
        }


        for (int i = 0; i < submitQuesAttemptList.size(); i++) {
            SubmitQuesAttempt submitQuesAttempt = submitQuesAttemptList.get(i);
            String quesId = submitQuesAttempt.getQuesId();
            String attempt = submitQuesAttempt.getAttempt();
            ExamStuQues examStuQues = new ExamStuQues();
            examStuQues.setUserId(stuId);
            examStuQues.setExamId(examId);

            //判断考试使用的试卷中是否有这个题目
            //试卷中存储的题目的id列表
            List<String> quesIds = new ArrayList<>();
            for (int k = 0; k < paperQuesList.size(); k++) {
                Paper.PaperQues paperQuestemp = paperQuesList.get(k);
                Question questiontemp = paperQuestemp.getQuestion();
                String quesIdtemp = questiontemp.getQuesId();
                quesIds.add(quesIdtemp);
            }
            if (!quesIds.contains(quesId)) {
                throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您提交的题目-答案列表中部分题目在试卷中不存在，请重试！");
            }
        }

        //将此次考试的信息插入数据库，同时计算考试成绩
        for (int i = 0; i < submitQuesAttemptList.size(); i++) {
            SubmitQuesAttempt submitQuesAttempt = submitQuesAttemptList.get(i);
            String quesId = submitQuesAttempt.getQuesId();
            String attempt = submitQuesAttempt.getAttempt();
            ExamStuQues examStuQues = new ExamStuQues();
            examStuQues.setUserId(stuId);
            examStuQues.setExamId(examId);

//            if(submitQuesAttempt.getAttempt() == null || submitQuesAttempt.getQuesId() == null
//                    || submitQuesAttempt.getQuesId().isEmpty() || submitQuesAttempt.getAttempt().isEmpty()){
//                throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您提交的题目-答案列表中不完整，请重试！");
//            }

            //判断考试使用的试卷中是否有这个题目
            //试卷中存储的题目的id列表
            List<String> quesIds = new ArrayList<>();
            for (int k = 0; k < paperQuesList.size(); k++) {
                Paper.PaperQues paperQuestemp = paperQuesList.get(k);
                Question questiontemp = paperQuestemp.getQuestion();
                String quesIdtemp = questiontemp.getQuesId();
                quesIds.add(quesIdtemp);
            }
            if (!quesIds.contains(quesId)) {
                throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "您提交的题目-答案列表中部分题目在试卷中不存在，请重试！");
            }

            examStuQues.setQuesId(quesId);
            examStuQues.setAttempt(attempt);
            //找到标准答案，判断对错
            //Question question = questionMapper.selectByPrimaryKey(quesId);
            Question question = questionService.getQuesById(quesId);
            String ans = question.getQuesAns();
            if (attempt.equals(ans)) {
                examStuQues.setIsCorrect((byte) 1);
                //计算总分
                for (int j = 0; j < paperQuesList.size(); j++) {
                    Paper.PaperQues paperQues = paperQuesList.get(j);
                    Question question1 = paperQues.getQuestion();
                    Integer score = paperQues.getScore();
                    if (question1.getQuesId().equals(quesId)) {
                        grade += score;
                    }
                }
            } else {
                examStuQues.setIsCorrect((byte) 0);
            }
            examStuQuesList.add(examStuQues);
            examStuQuesMapper.insert(examStuQues);
        }


        //增加exam_intern表数据
        ExamIntern examIntern = examInterns.get(0);
        examIntern.setUserId(stuId);
        examIntern.setExamId(examId);
        examIntern.setEnterTime(enterTime);
        examIntern.setGrade(grade);
        examInternMapper.deleteByExample(examInternExample);
        examInternMapper.insert(examIntern);

        return examStuQuesList;
    }

    @Override
    public UsersExam userExam(String userId, String examId) {
        List<UserQuestion> userQuestionList = new ArrayList<>();

        UsersExam usersExam = new UsersExam();
        usersExam.setUserId(userId);
        usersExam.setExamId(examId);
        //获取得到的信息
//        String userId = usersExam.getUserId();
//        String examId = usersExam.getExamId();
        if (userId == null || userId.isEmpty() || examId == null || examId.isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "传入的数据缺失，请重新上传");
        }

        //查询要找的实习生是否存在
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "你要查询的实习生不存在，请重新输入");
        }

        //查询要找的考试是否存在
        Exam exam = getExamById(examId);
        Exam exam1 = examMapper.selectByPrimaryKey(examId);
        if (exam1 == null) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "你要查询的考试不存在，请重新输入");
        }

        //检查实习生是否可以参加考试
        List<Exam.ExamStu> examStus = exam.getExamStus();
        List<String> examStutemp = new ArrayList<>();
        for (int i = 0; i < examStus.size(); i++) {
            Exam.ExamStu examStu = examStus.get(i);
            String examIdtemp = examStu.getStuId();
            examStutemp.add(examIdtemp);
        }
        if (!examStutemp.contains(userId)) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "你要查询的考试，该实习生无法参加，请重新输入");
        }

//        //处理考试已经过期的情形，实习生仍然可以查看试卷的题目以及答案
//        LocalDateTime ddl = exam1.getExamDdl();
//        LocalDateTime now = LocalDateTime.now();
//        System.out.println(ddl);
//        System.out.println(now);
//        if(now.isAfter(ddl)){
//            String examName = exam1.getExamName();
//            usersExam.setExamName(examName);
//
//            //找到相关试卷，加入总分
//            Paper paper = paperService.getPaperById(exam.getPaper().getPaperId());
//            Integer fullScore = paper.getPaperScore();
//            usersExam.setFullScore(fullScore);
//
//            //处理userQuestionList部分
//            List<UserQuestion> userQuestions = new ArrayList<>();
//            List<Paper.PaperQues> paperQuesList = paper.getPaperQuesList();
//            for(int i=0;i<paperQuesList.size();i++){
//                Paper.PaperQues paperQues = paperQuesList.get(i);
//                Question question = paperQues.getQuestion();
//                String quesId = question.getQuesId();
//                String quesAns = question.getQuesAns();
//                Byte isSingle = question.getIsSingle();
//                String quesDesc = question.getQuesDesc();
//                String quesOpA = question.getQuesOpA();
//                String quesOpB = question.getQuesOpB();
//                String quesOpC = question.getQuesOpC();
//                String quesOpD = question.getQuesOpD();
//                Integer score = paperQues.getScore();
//                UserQuestion userQuestion = new UserQuestion();
//                userQuestion.setQuesId(quesId);
//                userQuestion.setQuesAns(quesAns);
//                userQuestion.setIsSingle(isSingle);
//                userQuestion.setQuesDesc(quesDesc);
//                userQuestion.setQuesOpA(quesOpA);
//                userQuestion.setQuesOpB(quesOpB);
//                userQuestion.setQuesOpC(quesOpC);
//                userQuestion.setQuesOpD(quesOpD);
//                userQuestion.setQuesScore(score);
//
//                userQuestions.add(userQuestion);
//            }
//            usersExam.setUserQuestionList(userQuestions);
//            return usersExam;
//        }

        //查看实习生是否已经参加过了考试
        ExamInternExample examInternExample = new ExamInternExample();
        examInternExample.createCriteria().andExamIdEqualTo(examId).andUserIdEqualTo(userId)
                .andEnterTimeIsNotNull().andGradeIsNotNull();
        List<ExamIntern> examInterns = examInternMapper.selectByExample(examInternExample);


        //处理考试已经过期的情形，实习生仍然可以查看试卷的题目以及答案
        LocalDateTime ddl = exam1.getExamDdl();
        LocalDateTime now = LocalDateTime.now();
        if(examInterns.size() != 1 && now.isAfter(ddl)){
            String examName = exam1.getExamName();
            usersExam.setExamName(examName);

            //找到相关试卷，加入总分
            Paper paper = paperService.getPaperById(exam.getPaper().getPaperId());
            Integer fullScore = paper.getPaperScore();
            usersExam.setFullScore(fullScore);

            //处理userQuestionList部分
            List<UserQuestion> userQuestions = new ArrayList<>();
            List<Paper.PaperQues> paperQuesList = paper.getPaperQuesList();
            for(int i=0;i<paperQuesList.size();i++){
                Paper.PaperQues paperQues = paperQuesList.get(i);
                Question question = paperQues.getQuestion();
                String quesId = question.getQuesId();
                String quesAns = question.getQuesAns();
                Byte isSingle = question.getIsSingle();
                String quesDesc = question.getQuesDesc();
                String quesOpA = question.getQuesOpA();
                String quesOpB = question.getQuesOpB();
                String quesOpC = question.getQuesOpC();
                String quesOpD = question.getQuesOpD();
                Integer score = paperQues.getScore();
                UserQuestion userQuestion = new UserQuestion();
                userQuestion.setQuesId(quesId);
                userQuestion.setQuesAns(quesAns);
                userQuestion.setIsSingle(isSingle);
                userQuestion.setQuesDesc(quesDesc);
                userQuestion.setQuesOpA(quesOpA);
                userQuestion.setQuesOpB(quesOpB);
                userQuestion.setQuesOpC(quesOpC);
                userQuestion.setQuesOpD(quesOpD);
                userQuestion.setQuesScore(score);

                userQuestions.add(userQuestion);
            }
            usersExam.setUserQuestionList(userQuestions);
            return usersExam;
        }

        if (examInterns.size() != 1) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "查询到考试考生信息数据有误，请重试");
        }
        ExamIntern examIntern = examInterns.get(0);
        Integer grade = examIntern.getGrade();
        LocalDateTime enterTime = examIntern.getEnterTime();
        String examName = exam.getExamName();
        Paper paper = exam.getPaper();
        Integer fullScore = paper.getPaperScore();
        usersExam.setGrade(grade);
        usersExam.setEnterTime(enterTime);
        usersExam.setExamName(examName);
        usersExam.setFullScore(fullScore);

        //处理userQuestionList部分
        ExamStuQuesExample examStuQuesExample = new ExamStuQuesExample();
        examStuQuesExample.setOrderByClause("ques_id");
        examStuQuesExample.createCriteria().andExamIdEqualTo(examId).andUserIdEqualTo(userId);
        List<ExamStuQues> examStuQuesList = examStuQuesMapper.selectByExample(examStuQuesExample);
        List<Paper.PaperQues> paperQuesList = paper.getPaperQuesList();
        for (int i = 0; i < examStuQuesList.size(); i++) {
            //将得到的每一条数据拆解
            ExamStuQues examStuQues = examStuQuesList.get(i);
            String quesId = examStuQues.getQuesId();
            Byte isCorrect = examStuQues.getIsCorrect();
            String attempt = examStuQues.getAttempt();

            UserQuestion userQuestion = new UserQuestion();
            userQuestion.setQuesId(quesId);
            Question question = questionService.getQuesById(quesId);
            String quesAns = question.getQuesAns();
            Byte isSingle = question.getIsSingle();
            String quesDesc = question.getQuesDesc();
            String quesOpA = question.getQuesOpA();
            String quesOpB = question.getQuesOpB();
            String quesOpC = question.getQuesOpC();
            String quesOpD = question.getQuesOpD();

            Integer quesScore = 0;
            for (int j = 0; j < paperQuesList.size(); j++) {
                Question question1 = paperQuesList.get(j).getQuestion();
                Integer score = paperQuesList.get(j).getScore();
                String quesId1 = question1.getQuesId();
                if (quesId1.equals(quesId)) {
                    quesScore = score;
                }
            }
            if (quesScore == 0) {
                throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "题目分值查询异常，请重试");
            }

            Integer stuScore = quesScore;
            if (isCorrect == 1) {
                stuScore = quesScore;
            } else {
                stuScore = 0;
            }

            userQuestion.setQuesId(quesId);
            userQuestion.setQuesAns(quesAns);
            userQuestion.setIsSingle(isSingle);
            userQuestion.setQuesDesc(quesDesc);
            userQuestion.setQuesOpA(quesOpA);
            userQuestion.setQuesOpB(quesOpB);
            userQuestion.setQuesOpC(quesOpC);
            userQuestion.setQuesOpD(quesOpD);
            userQuestion.setIsCorrect(isCorrect);
            userQuestion.setQuesScore(quesScore);
            userQuestion.setAttempt(attempt);
            userQuestion.setStuScore(stuScore);

            userQuestionList.add(userQuestion);
        }

        usersExam.setUserQuestionList(userQuestionList);


        return usersExam;
    }


}
